<?php

namespace App\Services;

use App\Exceptions\GeneralException;
use App\Models\Role;
use App\Tools\Tree;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RoleService
{
    /**
     * 获取角色列表
     * @param $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getIndex($params)
    {
        $page = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['limit']) ? $params['limit'] : 10;
        $with = !empty($params['with']) ? $params['with'] : null;
        $query = Role::query();
        if (!empty($with)) {
            $query->with($with);
        }
        if (!empty($page) && !empty($limit)) {
            $list = $query->paginate($limit);
        } else {
            $list = $query->get();
        }

        return $list;
    }

    /**
     * 新增角色
     * @param $params
     * @return Role
     * @throws GeneralException
     */
    public function storeRole($params)
    {
        DB::beginTransaction();
        try {
            $role = new Role();
            $role->fill($params);
            $role->save();
            $role->privileges()->sync($params['renew']);
            Artisan::call('privileges:clear');
            DB::commit();
        } catch (\Exception $e) {
            Log::error('保存角色失败：'.$e->getMessage());
            DB::rollBack();
            throw new GeneralException('服务器错误');
        }
        return $role;
    }

    /**
     * 查看角色
     *
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function showRole(int $id)
    {
        $role = Role::query()->with('privileges')->find($id);
        $role->rolePrivileges = Tree::getTree($role->privileges->toArray());
        unset($role->privileges);
        return $role;
    }

    /**
     * 更新角色
     *
     * @param $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     * @throws GeneralException
     */
    public function updateRole($params)
    {
        DB::beginTransaction();
        try {
            $role = Role::query()->findOrFail($params['id']);
            $role->fill($params);
            $role->save();
            $role->privileges()->sync($params['renew']);
            Artisan::call('privileges:clear');
            DB::commit();
        } catch (\Exception $e) {
            Log::error('更新角色失败：'.$e->getMessage());
            DB::rollBack();
            throw new GeneralException('服务器错误');
        }

        return $role;
    }

    /**
     * 删除角色
     *
     * @param int $id
     * @return bool
     * @throws GeneralException
     */
    public function destroyRole(int $id)
    {
        /**
         * @var $role Role
         */
        $role = Role::query()->with('admins')->find($id);
        if ($role->admins->isNotEmpty()) {
            throw new GeneralException('该角色下有账号关联', 400);
        }
        DB::beginTransaction();
        try{
            $role->privileges()->detach();
            $role->delete();
        }catch (\Exception $exception){
            Log::error('删除角色失败：'.$exception->getMessage());
            DB::rollBack();
            throw new GeneralException('服务器错误');
        }

        Artisan::call('privileges:clear');
        return true;
    }
}
